import React, {Component} from 'react';
import {View, StyleSheet, Text, SectionList, findNodeHandle, UIManager, BackHandler} from 'react-native';
import {List, Toast} from '@ant-design/react-native';
import {connect} from 'react-redux';
import {saveSystem} from '~/store/system';
import {getCityListOfOpen, getPopularCityListOfOpen} from '~/api/public';

const mapGetter = (state) => {
    return {
        system: state.system,
    };
};

const mapSetter = (dispatch) => {
    return {
        onSave: (data) => {
            dispatch(saveSystem(data));
        },
    };
};

const HEAD_HEIGHT = 40;
const ITEM_HEIGHT = 40;
const POPULAR_TITLE = '热门城市';

class CityScreen extends Component {
    static navigationOptions = ({navigation}) => {
        return {
            title: '选择城市',
            headerLeft: () => null,
        };
    };

    constructor(props) {
        super(props);
        this.letter_list = [];
        this.letter_offset = 0;
        this.current_index = -1;
        this.city_list = [];
        this.layout_list = [];
    }

    componentDidMount() {
        this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
            return true;
        });
        this.initData();
        this.initCityData();
    }

    componentWillUnmount() {
        this.backHandler && this.backHandler.remove();
    }

    initData = () => {
        this.city_list.push({
            title: POPULAR_TITLE,
            data: [{list: this.props.system.popular_city}],
        });
        this.props.system.city_list.forEach((city) => {
            this.city_list.push({
                title: city.letter,
                data: city.list,
            });
        });
    };

    initCityData = () => {
        (async () => {
            await getPopularCityListOfOpen().then((r) => {
                if (r.code === 0) {
                    this.props.onSave({popular_city: r.data});
                }
            });
            await getCityListOfOpen().then((r) => {
                if (r.code === 0) {
                    let city_list = [];
                    let temp_list = [];
                    let letter = '';
                    r.data.forEach((item) => {
                        if (item.FirstLetter !== letter) {
                            if (letter !== '') {
                                city_list.push({
                                    letter: letter,
                                    list: temp_list,
                                });
                            }
                            letter = item.FirstLetter;
                            temp_list = [];
                        }
                        temp_list.push(item);
                    });
                    city_list.push({
                        letter: letter,
                        list: temp_list,
                    });
                    this.props.onSave({city_list});
                }
            });
            this.city_list = [];
            this.initData();
            this.setState({});
        })();
    };

    setLetterOffset = () => {
        const handle = findNodeHandle(this.letterView);
        UIManager.measure(handle, (x, y, width, height, pageX, pageY) => {
            this.letter_offset = pageY;
        });
    };

    onMoveLetter = (evt) => {
        const y = parseInt(evt.nativeEvent.pageY, 10);
        let index = parseInt((y - this.letter_offset) / 20, 10);
        if (index < 0) {
            index = 0;
        }
        if (index >= this.props.system.city_list.length) {
            index = this.props.system.city_list.length - 1;
        }
        this.onGoLetter(index);
    };

    onGoLetter = (index) => {
        this.SectionList.scrollToLocation({
            itemIndex: 0,
            sectionIndex: index + 1,
        });
    };

    onSelectLetter = (info) => {
        if (info.viewableItems.length === 0) {
            return;
        }
        let title = info.viewableItems[0].section.title;
        let index = this.props.system.city_list.findIndex((city) => city.letter === title);
        if (this.current_index !== index) {
            if (this.current_index >= 0) {
                this.letter_list[this.current_index].setNativeProps({
                    style: {
                        color: 'gray',
                    },
                });
            }
            this.current_index = index;
            if (index >= 0) {
                this.letter_list[index].setNativeProps({
                    style: {
                        color: '#ff3733',
                    },
                });
            }
        }
    };

    calcItemLayout = (evt) => {
        let layoutList = [];
        let layoutIndex = 0;
        let layoutOffset = 0;
        this.city_list.forEach((section) => {
            layoutList.push({
                index: layoutIndex++,
                length: HEAD_HEIGHT,
                offset: layoutOffset,
            });
            layoutOffset += HEAD_HEIGHT;
            if (section.title === POPULAR_TITLE) {
                const height = parseInt(evt.nativeEvent.layout.height, 10);
                layoutList.push({
                    index: layoutIndex++,
                    length: height,
                    offset: layoutOffset,
                });
                layoutOffset += height;
            } else {
                section.data.forEach(() => {
                    layoutList.push({
                        index: layoutIndex++,
                        length: ITEM_HEIGHT,
                        offset: layoutOffset,
                    });
                    layoutOffset += ITEM_HEIGHT;
                });
            }
            layoutList.push({
                index: layoutIndex++,
                length: 0,
                offset: layoutOffset,
            });
        });

        this.layout_list = layoutList;
    };

    onSelectCity = (city) => {
        this.props.onSave({
            city_id: city.PuCityID,
            city: city.CityName,
        });
        this.props.navigation.state.params.updateCityName(city.CityName, city.PuCityID);
        this.props.navigation.pop();
    };

    renderPopular = (item) => {
        return (
            <View style={styles.popularView}>
                <Text
                    onPress={() => {
                        this.onSelectCity(item);
                    }}>
                    {item.CityName}
                </Text>
            </View>
        );
    };

    renderItem = (city, title) => {
        if (title === POPULAR_TITLE) {
            return (
                <List onLayout={this.calcItemLayout}>
                    <List.Item>
                        <View style={styles.popularList}>{city.list.map((item) => this.renderPopular(item))}</View>
                    </List.Item>
                </List>
            );
        } else {
            return (
                <List style={{height: ITEM_HEIGHT}}>
                    <List.Item
                        onPress={() => {
                            this.onSelectCity(city);
                        }}>
                        {city.CityName}
                    </List.Item>
                </List>
            );
        }
    };

    render() {
        return (
            <View style={styles.mainView}>
                <SectionList
                    sections={this.city_list}
                    onViewableItemsChanged={this.onSelectLetter}
                    showsVerticalScrollIndicator={false}
                    keyExtractor={(item, index) => item.PuCityID + '-' + index}
                    renderItem={({item, section: {title}}) => this.renderItem(item, title)}
                    renderSectionHeader={({section: {title}}) => <List style={{height: HEAD_HEIGHT}} renderHeader={title} />}
                    getItemLayout={(data, index) => {
                        if (this.layout_list.length > 0) {
                            return this.layout_list.find((item) => item.index === index);
                        } else {
                            return {
                                index: index,
                                offset: 0,
                                length: 0,
                            };
                        }
                    }}
                    ref={(ref) => (this.SectionList = ref)}
                />
                <View style={styles.letterView}>
                    <View
                        onTouchMove={(evt) => this.onMoveLetter(evt)}
                        onTouchEnd={(evt) => this.onMoveLetter(evt)}
                        ref={(ref) => (this.letterView = ref)}
                        onLayout={this.setLetterOffset}>
                        {this.props.system.city_list.map((item, index) => {
                            return (
                                <Text style={styles.letterItem} key={index} ref={(ref) => this.letter_list.push(ref)}>
                                    {item.letter}
                                </Text>
                            );
                        })}
                    </View>
                </View>
            </View>
        );
    }
}

export default connect(mapGetter, mapSetter)(CityScreen);

const styles = StyleSheet.create({
    mainView: {
        flex: 1,
    },
    listView: {
        flex: 1,
    },
    popularTitle: {
        color: 'gray',
        marginVertical: 10,
    },
    popularList: {
        flexWrap: 'wrap',
        flexDirection: 'row',
    },
    popularView: {
        paddingVertical: 5,
        paddingHorizontal: 10,
        backgroundColor: '#00000010',
        borderRadius: 5,
        marginRight: 15,
        marginVertical: 5,
    },
    letterView: {
        position: 'absolute',
        right: 0,
        backgroundColor: 'transparent',
        alignItems: 'center',
        justifyContent: 'center',
        flex: 1,
        height: '100%',
    },
    letterItem: {
        fontSize: 12,
        height: 20,
        lineHeight: 20,
        paddingHorizontal: 15,
        textAlign: 'center',
        fontWeight: '500',
        color: 'gray',
    },
});
